<?php

namespace App\Http\Controllers\Alipay;

use Carbon\Carbon;

use App\Service\WdhService;

use Illuminate\Http\Request;

use App\Models\ConfigureFunction;  //配置信息

use App\Models\Customer\Customer;  //会员主表

use App\Models\Alipay\AlipayCustomer;  //支付宝会员主表

use App\Models\Alipay\AlipayCustomerCard;  //会员卡主表

use App\Models\Alipay\AlipayCustomerCardMap;  //会员卡映射表

use Illuminate\Support\Facades\Redis as Redis;

use App\Http\Controllers\Controller;

use App\Service\Alipay\AlipayRequestService;

class AlipayCustomerCardController extends Controller
{

    private $client;

    public function __construct()
    {
        $this->client = new AlipayRequestService();
    }


    /**
     * 领卡页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function check( Request $request )
    {

        $session_id = session_id();
        $host = $request->getSchemeAndHttpHost();


        $redis_index = 'ALIPAY_USER_ID_' . $session_id;
        $is_alipay_card = 1; // 1 未领取会员卡 2已领取会员卡


        if ( Redis::exists($redis_index) ) {
            $user_id = Redis::get($redis_index);
            if ( $user_id ) {
                $card_map =  AlipayCustomerCardMap::where(['alipay_user_id' => $user_id ])->first();
                if ( $card_map && isset($card_map['alipay_user_id']) && $card_map['alipay_user_id'] ) {
                    $is_alipay_card = 2;
                }
            }
        } else {

            Redis::setex( 'G_UNION_LOGIN_REDIRECT_URL' . $session_id, 86400, urlencode($host .'/alipay/customer/card/check'));
            $host = $request->getSchemeAndHttpHost();
            $app_id = ConfigureFunction::getConfigureField(42, 'app_id');
            $http_array = [
                'app_id' => $app_id,
                'scope' => 'auth_base',
                'redirect_uri' => $host . '/lar/alipay/auth/notify'
            ];

            $requestURL = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?' . http_build_query( $http_array );

            return redirect()->to($requestURL);

        }

        $open_card_url = '';
        $card_data = AlipayCustomerCard::find(1);

        if ( isset($card_data['activateUrl']) && !empty($card_data['activateUrl']) ) {
            $open_card_url = $card_data['activateUrl'];
        }

        return view ('alipay/xfsg/check', [ 'open_card_url' => $open_card_url, 'is_alipay_card' => $is_alipay_card]);

    }


    /**
     * 领卡完成页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function complete( )
    {
        return view ('alipay/xfsg/complete');
    }


    /**
     * 领取会员卡
     * @param Request $request
     * @return string
     */
    public function apply(Request $request)
    {

        /*
         * 1. auth_code换取access_token与user_id
         * 2. 查询用户提交的会员卡表单信息
         * 3. 网站会员登录/注册
         * 4. 线下系统开卡/绑卡
         * 5. 获取会员详情->保存支付宝会员信息
         * 6. 支付宝会员卡开卡
         * 7. 开卡成功后处理
         */

        $template_id = $request->input('template_id');
        $request_id = $request->input('request_id');
        $auth_code = $request->input('auth_code');
        $shop_id = $request->input('shop_id', '');
        $redis_index = 'WDH_ALIPAY_MEMBER_CARD_REQUEST_ID_'. $request_id;

        if (empty($template_id) || empty($template_id) || empty($auth_code)) {
           $this->notice();
        }

        $oauth = $this->oauth($auth_code);
        if ( empty($oauth) ) {
            //已经领卡跳转成功领卡页（防止刷新提交）
            if ( Redis::exists($redis_index) ) {
                $callBackUrl = Redis::get($redis_index);
                if ( $callBackUrl ) {
                    return view ('alipay/xfsg/complete', ['call_back_url' => $callBackUrl]);
                }
            }

           $this->notice();
        }


        //查询用户提交的会员卡表单信息
        $user_form = $this->getActivateForm($template_id, $request_id, $oauth);
        if ( empty($user_form) || empty($user_form['mobile'])) {
           $this->notice();
        }


        /**
         * 3. 网站会员登录/注册
         * 4. 线下系统开卡/绑卡
         */
        $customer = Customer::select('pcustID', 'pwd', 'custID', 'cardNo')->where(['custID'=> $user_form['mobile']])->first();
        if ( !$customer ) {
            $customer = Customer::select('pcustID','pwd','custID', 'cardNo')->where(['mobile'=> $user_form['mobile']])->first();
            if ( !$customer ) {
                $pwd = get_random_string(8, 'number');
                //注册会员
                $customer = new Customer();
                $customer->uuid = makeUuid();
                $customer->timeStamp = Carbon::now();
                $customer->creator = $user_form['mobile'];
                $customer->createTime = Carbon::now();
                $customer->custID = $user_form['mobile'];
                $customer->pcustID = generate_seqno('seqno_customer', '', true);
                $customer->useFlg = 1;
                $customer->custType = 1;
                $customer->pwd = md5($pwd);
                $customer->sexy = $user_form['sexy'];
                $customer->birthday = $user_form['birthday'];
                $customer->email = $user_form['email'];
                $customer->identityCard = $user_form['identityCard'];
                $customer->mobile = $user_form['mobile'];
                $customer->save();
            }
        }

        if ( !$customer->cardNo ) {
            //调用开卡接口
            WdhService::openCard([
                'pcustID' => $customer->pcustID,
                'custID' => $customer->custID,
                'mobile' => $user_form['mobile']
            ]);
        }

        //检查线下卡号信息  存在现在会员卡信息则开支付宝会员卡
        $customer = Customer::find( $customer->pcustID );
        if ( !$customer->cardNo ) {
           $this->notice();
        }


        //获取支付宝会员信息
        $cust_detail = $this->getCustInfo($oauth['access_token']);
        if ( empty($cust_detail) ) {
           $this->notice();
        }


        //保存支付宝会员
        $alipay_customer = AlipayCustomer::where(['alipay_user_id' => $oauth['user_id']])->first();
        if ( empty($alipay_customer) ) {
            $alipay_customer = new AlipayCustomer();
            $alipay_customer->uuid = makeUuid();
            $alipay_customer->timeStamp = Carbon::now();
            $alipay_customer->createTime = Carbon::now();
            $alipay_customer->creator = $customer->pcustID;
            $alipay_customer->alipay_user_id = $oauth['user_id'];
            $alipay_customer->pcustID = $customer->pcustID;
            $alipay_customer->follow = 0;
            $alipay_customer->mobile = $user_form['mobile'];
            if ( isset($cust_detail['nick_name']) ) {
                $alipay_customer->nick_name = $cust_detail['nick_name'];
            }
            if ( isset($cust_detail['province']) ) {
                $alipay_customer->province = $cust_detail['province'];
            }
            if ( isset($cust_detail['city']) ) {
                $alipay_customer->city = $cust_detail['city'];
            }
            if ( isset($cust_detail['gender']) ) {
                if( $cust_detail['gender'] == 'm' || $cust_detail['gender'] == 'M') {
                    $alipay_customer->sex = 1;
                }
                if( $cust_detail['gender'] == 'f' || $cust_detail['gender'] == 'F') {
                    $alipay_customer->sex = 2;
                }
            }
            if ( isset($cust_detail['avatar']) ) {
                $alipay_customer->avatar = $cust_detail['avatar'];
            }
            $alipay_customer->save();
        }

        if ( !$customer->cardNo ) {
           $this->notice();
        }

        //支付宝会员卡开卡
        $open_card = [
            'card_template_id' => $template_id,
            'external_card_no' => $customer->cardNo,
            'user_uni_id' => $oauth['user_id'],
        ];

        $open_card_res = $this->openCard( $open_card );
        if ( empty($open_card_res) ) {
            $this->notice();
        }


        $card_map =  AlipayCustomerCardMap::where(['pcustID' => $customer->pcustID ])->first();
        if ( empty($card_map) ) {
            $card_map = new AlipayCustomerCardMap();
            $card_map->uuid = makeUuid();
            $card_map->timeStamp = Carbon::now();
            $card_map->createTime = Carbon::now();
            $card_map->creator = $user_form['mobile'];
            $card_map->alipay_user_id = $oauth['user_id'];
            $card_map->cardCode = $customer->cardNo;
            $card_map->cardNo = $open_card_res['card_info']['biz_card_no'];
            $card_map->pcustID = $customer->pcustID;
            $card_map->save();
        } else {
            AlipayCustomerCardMap::where(['pcustID' => $customer->pcustID ])->update(['cardNo' => $open_card_res['card_info']['biz_card_no'] ]);
        }

        /**
         * 开卡成功后处理
         * 1. 赠送卡券
         * 2. 同步支付宝会员卡的会员信息到线上线下crm
         * 3. 领取成功后跳转到领取成功页
         */

        //赠送卡券 （失败再发放一次）
//        $send_active_res = $this->sendConpous( $oauth['user_id'], 2017102310076000000018458703, $shop_id );
//        if ( !$send_active_res ) {
//             $this->sendConpous( $oauth['user_id'], 2017102310076000000018458703, $shop_id );
//        }

        //报名活动 （失败再发放一次）
//        $send_conpous_res = $this->sendConpous( $oauth['user_id'], 2017102310076000000018408920, $shop_id );
//        if ( !$send_conpous_res ) {
//             $this->sendConpous( $oauth['user_id'], $shop_id );
//        }




        //更新会员信息
        WdhService::customerEdit([
            'pcustID' => $customer->pcustID,
            'custname' => $user_form['custname'],
            'mobile' => $user_form['mobile'],
            'birthday' => $user_form['birthday'],
            'sexy' => $user_form['sexy']
        ]);

        $callBackUrl = $this->cardQuery( $open_card_res['card_info']['biz_card_no'] );
        if ( empty($callBackUrl) ) {
            $this->notice();
        }

        Redis::setex( $redis_index, 7200, $callBackUrl);

        return view ('alipay/xfsg/complete', ['call_back_url' => $callBackUrl]);

    }



    private function getActivateForm($template_id, $request_id, $oauth)
    {

        //查询用户提交的会员卡表单信息
        $biz_content = [
            'biz_type' => 'MEMBER_CARD',
            'template_id' => $template_id,
            'request_id' => $request_id
        ];
        $this->client->auth_token = $oauth['access_token'];
        $this->client->method = 'alipay.marketing.card.activateform.query';
        $this->client->biz_content = json_encode( $biz_content );
        $this->client->response_key = 'alipay_marketing_card_activateform_query_response';
        $activateForm = $this->client->query();

        if ( $activateForm['code'] != 200 || !$activateForm['data']['infos']) {
            return null;
        }

        $return_data = [
            'mobile' => '',
            'sexy' => 0,
            'custname' => '',
            'birthday' => '',
            'identityCard' => '',
            'email' => '',
        ];


        $cust_info = json_decode( $activateForm['data']['infos'] ,true);

        foreach ( $cust_info as  $infos ) {
            if ( isset($infos['OPEN_FORM_FIELD_MOBILE']) ) {
                $return_data['mobile'] = $infos['OPEN_FORM_FIELD_MOBILE'];
            }
            if ( isset($infos['OPEN_FORM_FIELD_NAME']) ) {
                $return_data['custname'] = $infos['OPEN_FORM_FIELD_NAME'];
            }
            if ( isset($infos['OPEN_FORM_FIELD_BIRTHDAY_WITH_YEAR']) ) {
                $return_data['birthday'] = $infos['OPEN_FORM_FIELD_BIRTHDAY_WITH_YEAR'];
            }
            if ( isset($infos['OPEN_FORM_FIELD_IDCARD']) ) {
                $return_data['birthday'] = $infos['OPEN_FORM_FIELD_IDCARD'];
            }
            if ( isset($infos['OPEN_FORM_FIELD_EMAIL'] ) ) {
                $return_data['birthday'] = $infos['OPEN_FORM_FIELD_EMAIL'];
            }

            if( isset($infos['OPEN_FORM_FIELD_GENDER']) ) {
                if( $infos['OPEN_FORM_FIELD_GENDER'] == '男') {
                    $return_data['sexy'] = 1;
                } elseif( $infos['OPEN_FORM_FIELD_GENDER'] == '女') {
                    $return_data['sexy'] = 2;
                }
            }

        }

        return $return_data;

    }

    /**
     *
     * 会员卡开卡
     * @param $args_data
     * @return array
     */
    public function openCard( $args_data )
    {

        if ( !isset($args_data['card_template_id']) || empty($args_data['card_template_id']) ) {
            return ['code' => 100001, 'message' => '卡模板Id不能为空'];
        }


        if ( !isset($args_data['external_card_no']) || empty($args_data['external_card_no']) ) {
            return ['code' => 100002, 'message' => '用户线下卡号不能为空'];
        }

        if ( !isset($args_data['user_uni_id']) || empty($args_data['user_uni_id']) ) {
            return ['code' => 100003, 'message' => '支付宝会员id不能为空'];
        }

        $card_user_info = [
            'user_uni_id' => $args_data['user_uni_id'],
            'user_uni_id_type' => 'UID'
        ];

        $card_ext_info = [
            'external_card_no' => $args_data['external_card_no'],
            'open_date' => date('Y-m-d H:i:s'),
            'valid_date' => '2200-01-01 00:00:00',
        ];

        $biz_content = [
            'out_serial_no' => makeUuid(),
            'card_template_id' => $args_data['card_template_id'],
            'card_user_info' => $card_user_info,
            'card_ext_info' => $card_ext_info
        ];

        $this->client->method = 'alipay.marketing.card.open';
        $this->client->biz_content = json_encode( $biz_content );
        $this->client->response_key = 'alipay_marketing_card_open_response';
        $res = $this->client->query();

        if ( $res['code'] != 200  ) {
            return null;
        }

        return $res['data'];

    }


    /**
     * auth_code换取access_token与user_id
     * @param $auth_code
     * @return array
     */
    private function oauth( $auth_code )
    {
        if ( empty($auth_code) ) {
            return ['code' => 100001, 'message' => '授权的auth_code不能为空'];
        }

        $this->client->method = 'alipay.system.oauth.token';
        $this->client->biz_content = [
            'code' => $auth_code,
            'grant_type' => 'authorization_code'
        ];
        $this->client->response_key = 'alipay_system_oauth_token_response';

        $res = $this->client->query();
        if ($res['code'] != 200) {
            return null;
        }

        return $res['data'];

    }


    /**
     * 会员卡查询（主要获取跳转链接）
     * @param $target_card_no
     * @return array
     */
    private function cardQuery( $target_card_no )
    {
        if ( empty($target_card_no) ) {
            return null;
        }
        $this->client->method = 'alipay.marketing.card.query';
        $this->client->biz_content = json_encode([
            'target_card_no' => $target_card_no,
            'target_card_no_type' => 'BIZ_CARD'
        ]);
        $this->client->response_key = 'alipay_marketing_card_query_response';

        $res = $this->client->query();
        if ($res['code'] != 200 ) {
            return null;
        }

        return $res['data']['schema_url'];

    }


    /**
     * 查询会员详情
     * @param $access_token
     * @return array
     */
    private function getCustInfo( $access_token )
    {
        if ( empty($access_token) ) {
            return null;
        }
        $this->client->auth_token = $access_token;
        $this->client->method = 'alipay.user.info.share';
        $this->client->biz_content = '';
        $this->client->response_key = 'alipay_user_info_share_response';

        $res = $this->client->query();
        if ($res['code'] != 200 ) {
            return null;
        }

        return $res['data'];

    }



    /**
     * 领会员卡送优惠劵
     * @param int $user_id 支付宝会员id
     *        int $item_id 触发权益的优惠id
     *        int $shop_id 门店id
     * @return null
     */
    private function sendConpous( $user_id, $item_id, $shop_id = '' )
    {
        $biz_content = [
            'out_biz_no' => makeUuid(),
            'item_id' => $item_id,
            'user_id' => $user_id,
            'shop_id' => $shop_id,
            'discount_type' => 'ITEM',
            'channel' => 'alipay'
        ];

        $this->client->method = 'koubei.marketing.campaign.benefit.send';
        $this->client->biz_content = json_encode($biz_content);
        $this->client->response_key = 'koubei_marketing_campaign_benefit_send_response';

        $res = $this->client->query();
        if ($res['code'] != 200 ) {
            return null;
        }

        return $res['data'];

    }

    /**
     * 查询微信会员详情
     * @return array
     */
    private function notice( )
    {
        $alipay_card = AlipayCustomerCard::find(1);
        $html_str = '<!DOCTYPE html><html><title>开卡失败</title><body>';
        $html_str .= '<p>开卡错误！</p>';
        $html_str .= '<H3><a href="' . $alipay_card['activateUrl'] . '">重新开卡</a></H3>';
        $html_str .= '</body></html>';

        die($html_str);

    }



}